<template>
  <div class="flex-1 page_contain">
    <div class="app-container">
      <!-- 搜索框 -->
      <div class="search-container">
        <el-form :model="searchParam" :inline="true" label-width="95px">
          <el-form-item label="工段">
            <el-select
              v-model="searchParam.workshopSectionId"
              placeholder="请选择工段"
              clearable
              filterable
              @change="changeWorkshopSection"
            >
              <el-option
                v-for="item in workshopSectionList"
                :key="item.id"
                :label="item.workshopSectionCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="工序">
            <el-select
              v-model="searchParam.processCode"
              placeholder="请选择工序"
              clearable
              filterable
              @change="processChange"
            >
              <el-option
                v-for="item in processCodeList"
                :key="item.processCode"
                :label="item.processName"
                :value="item.processCode"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="生产线">
            <el-select
              v-model="searchParam.processEquipId"
              placeholder="请选择生产线"
              clearable
              filterable
              @change="processEquipChange"
            >
              <el-option
                v-for="item in processEquipList"
                :key="item.processEquipId"
                :label="item.processEquipCode"
                :value="item.processEquipId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设备">
            <el-select
              v-model="searchParam.deviceIds"
              placeholder="请选择设备"
              clearable
              filterable
              multiple
              collapse-tags
              collapse-tags-tooltip
              @change="equipChange"
              class="select-device"
            >
              <el-option
                v-for="item in equipList"
                :key="item.equipId"
                :label="item.equipName"
                :value="item.equipId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="产品">
            <el-select
              v-model="searchParam.productModel"
              placeholder="请选择产品"
              clearable
              filterable
              :filter-method="customFilter"
              @change="productChange"
            >
              <el-option
                v-for="item in filteredOptions"
                :key="item.productModel"
                :label="item.productModel"
                :value="item.productModel"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="参数类型">
            <el-select
              v-model="searchParam.processDataType"
              placeholder="请选择参数类型"
              clearable
              filterable
              @change="processTypeChange"
            >
              <el-option label="工艺加工参数" value="2" />
              <el-option label="工艺过程参数" value="3" />
            </el-select>
          </el-form-item>

          <el-form-item label="参数名称">
            <el-select
              v-model="searchParam.parameterName"
              placeholder="请选择参数名称"
              clearable
              filterable
              :disabled="!searchParam.deviceIds.length"
              @change="processParameterChange"
            >
              <el-option
                v-for="(item, index) in collectParamList"
                :key="index"
                :label="item.parameterDesc"
                :value="item.parameterName"
              />
              <!-- <el-option
                v-for="(item, index) in collectParamList"
                :key="index"
                :label="item.parameterName"
                :value="item.id"
              /> -->
            </el-select>
          </el-form-item>
          <el-form-item label="监控结果">
            <el-select
              v-model="searchParam.monitorResult"
              placeholder="请选择监控结果"
              clearable
              filterable
            >
              <el-option label="全部" value="" />
              <el-option label="未超控制范围" value="1" />
              <el-option label="超过控制范围" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="监控时间">
            <el-date-picker
              v-model="searchParam.collectionTimeSearch"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="getPointTime"
            />
          </el-form-item>
          <el-form-item v-if="activeTabs == '1'" label="显示近">
            <el-input
              v-model="searchParam.pointCount"
              placeholder="请输入"
              clearable
              @keyup.enter="getSingleData"
              style="width: 190px"
            >
              <template #append>点</template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <i-ep-search />
              搜索
            </el-button>
            <el-button @click="handleReset">
              <i-ep-refresh />
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 列表 -->
      <el-tabs
        type="border-card"
        @tab-click="tabClickHandle"
        v-model="activeTabs"
      >
        <el-tab-pane label="详细数据"
          ><el-table
            ref="dataTableRef"
            v-loading="loading"
            :data="tableData"
            highlight-current-row
            border
            :maxHeight="tableHeight"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              label="工序"
              prop="processCode"
              fixed="left"
              min-width="120"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              label="设备编号"
              prop="deviceCode"
              min-width="120"
              align="center"
              fixed="left"
              show-overflow-tooltip
            />
            <el-table-column
              label="设备名称"
              prop="deviceName"
              min-width="150"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              label="产品型号"
              prop="productModel"
              align="center"
              min-width="140"
              show-overflow-tooltip
            />

            <el-table-column
              label="采集时间"
              prop="collectionTime"
              min-width="160"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              label="参数类型"
              prop="processDataType"
              min-width="120"
              align="center"
              show-overflow-tooltip
            >
              <template #default="scope">
                <el-tag v-if="scope.row.processDataType == 2">加工参数</el-tag>
                <el-tag type="success" v-if="scope.row.processDataType == 3"
                  >过程参数</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column
              label="参数描述"
              prop="parameterDesc"
              min-width="170"
              align="left"
              show-overflow-tooltip
            />

            <el-table-column
              label="采集值"
              prop="parameterValue"
              min-width="120"
              align="right"
              show-overflow-tooltip
            />
            <el-table-column
              label="参考值"
              prop="referenceValue"
              min-width="120"
              align="right"
              show-overflow-tooltip
            />
            <el-table-column
              label="控制范围"
              min-width="160"
              align="right"
              show-overflow-tooltip
            >
              <template #default="scope">
                <span
                  v-if="scope.row.lowerLimitValue == scope.row.upperLimitValue"
                  >{{ scope.row.lowerLimitValue ?? "" }}</span
                >
                <span v-else
                  >{{ scope.row.lowerLimitValue }} -
                  {{ scope.row.upperLimitValue }}</span
                >
              </template>
            </el-table-column>
            <el-table-column label="监控结果" align="center" min-width="150">
              <template #default="scope">
                <el-tag v-if="scope.row.monitorResult == 1" type="warning"
                  >变更未超控制范围</el-tag
                >
                <el-tag v-if="scope.row.monitorResult == 2" type="danger"
                  >变更超过控制范围</el-tag
                >
                <el-tag
                  v-if="
                    scope.row.monitorResult != 2 && scope.row.monitorResult != 1
                  "
                  type="success"
                  >正常</el-tag
                >
              </template>
            </el-table-column>
            <!-- 暂时没有工位字段 -->
            <!-- <el-table-column
            label="工位"
            prop="remarks"
            min-width="150"
            align="center"
            show-overflow-tooltip
          /> -->
          </el-table>

          <el-pagination
            :background="true"
            :current-page="pageable.pageNum"
            :page-size="pageable.pageSize"
            :page-sizes="[10, 25, 50, 100]"
            :total="pageable.total"
            layout="total, sizes, prev, pager, next, jumper"
            class="mt-[20px]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        /></el-tab-pane>
        <el-tab-pane label="趋势图" class="chart_tab">
          <div
            v-if="singleLoading"
            v-loading="true"
            class="w-full h-[400px]"
          ></div>
          <!-- 数据为空 -->
          <div v-if="!singleLoading && !singleData">
            <el-empty description="暂无数据" />
          </div>
          <div v-if="singleData" class="flex">
            <psmParamLineChartDouble
              key="1"
              id="1"
              :showName="true"
              :seriesData="singleData"
            />
            <div
              class="h-[430px] overflow-y-auto double-list w-[180px] pr-[10px]"
            >
              <el-descriptions
                v-for="(item, index) in singleData.doubleData"
                :key="index"
                :title="item.equipName || '--'"
                :column="1"
                size="small"
                :class="`doubleData${index}`"
                border
              >
                <el-descriptions-item label="参考值">{{
                  item.parameterStandards ?? ""
                }}</el-descriptions-item>
                <el-descriptions-item label="控制上限">{{
                  item.upperLimitValue ?? ""
                }}</el-descriptions-item>
                <el-descriptions-item label="控制下限">{{
                  item.lowerLimitValue ?? ""
                }}</el-descriptions-item>
                <el-descriptions-item label="取样频率：">{{
                  item.parameterSampleRate ?? ""
                }}</el-descriptions-item>
                <el-descriptions-item label="监控数据类型：">{{
                  item.monitorDataType
                    ? dictionaryStore.filterDictName(
                        "PsmMonitorDataType",
                        item.monitorDataType
                      )
                    : ""
                }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 工单弹窗 -->
    <psmworkorder-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
      key="1"
    />
  </div>
</template>

<script lang="ts" setup>
import request from "@/utils/request";
import { useTable, useComputeTableHeight } from "@/utils/useTable";
import router from "@/router";
import dayjs from "dayjs";
import { getMdmproductinfosApi1 } from "@/utils/commonData";
import psmParamLineChart from "@/views/psm/psmParamQuery/components/psmParamLineChart.vue";
import { getSingleDataMock } from "@/views/pcm/pcmMonitoring/index";
import psmworkorderEdit from "@/views/pcm/psmworkorder/components/psmworkorder-edit.vue";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import _ from "lodash-es";

defineOptions({
  name: "PSMPSMPARAMQUERY",
  inheritAttrs: false,
});

function handleReset() {
  router.go(0);
}

const activeTabs = ref("0");
function handleSearch() {
  if (activeTabs.value == "1") {
    getSingleData();
    search();
  } else {
    if (!searchParam.value.collectionTimeStart) {
      ElMessage.error("请选择监控时间");
      return;
    }
    let startTime = dayjs(searchParam.value.collectionTimeStart); // 开始时间
    let endTime = dayjs(searchParam.value.collectionTimeEnd); // 结束时间
    if (endTime.diff(startTime, "hour") > 24 * 7) {
      ElMessage.error("监控时间不能超过七天");
      return;
    }
    search();
  }
}

// 请求参数
const requestApi = "/dmpDosPcm/psmprocessdata/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  pointCount: "100",
  processCode: "", // 工序编号
  processId: "", // 工序id
  // deviceCode: "", // 设备编号
  // deviceId: "", // 设备id
  deviceIds: [],
  processDataType: "", // 参数类别
  parameterName: "", // 工艺参数
  parameterDesc: "", // 工艺描述
  // productId: "", // 产品型号
  monitorResult: "", // 监控结果
  programName: "", // 程序名
  productModel: "", // 产品型号
  // 监控时间
  collectionTimeStart: dayjs(Date.now())
    .subtract(7, "day")
    .format("YYYY-MM-DD"),
  collectionTimeEnd: dayjs(Date.now()).format("YYYY-MM-DD"),
  collectionTimeSearch: [
    dayjs(Date.now()).subtract(7, "day").format("YYYY-MM-DD"),
    dayjs().format("YYYY-MM-DD"),
  ],
  // 监控数据类型
  monitorDataType: "",
  processEquipId: "", // 生产线
  partName: "",
};

const deleteParam = {
  api: "/system/sysRole/delete",
  data: {},
};

// 如果初始化表格需要排序=》const initParam = reactive({sort:''});
// 监听页面 initParam 改化，重新获取表格数据
// watch(() => initParam, getTableList, { deep: true });

// 数据请求错误后处理
function requestError() {}

// 数据请求错误后处理
// function dataCallBack() {}   //需要处理
// 定义tableHeight, 将计算注入dataCallBack回调中
const tableHeight = ref();
function dataCallBack(data: any) {
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight() - 35;
  }, 100);
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  loading,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError,
  deleteParam
);

// 获取产品型号列表
const productList = ref<any>([]);
const filteredOptions = ref<any>([]);
async function getProductList() {
  const list: any = await getMdmproductinfosApi1({
    deviceIds: searchParam.value.deviceIds,
  });
  productList.value = list || [];
  filteredOptions.value = [...productList.value];
}

// 使用 debounce 包装过滤方法
const customFilter = _.debounce((query: any) => {
  if (!query) {
    filteredOptions.value = [...productList.value];
    return;
  }
  filteredOptions.value = productList.value.filter((option: any) =>
    option.productModel.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

function productChange(id: string) {
  if (id) {
    const current: any =
      productList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.productCode = current.productCode || "";
  } else {
    searchParam.value.productCode = "";
  }
}

// 获取工序列表
const processCodeList: any = ref([]);
async function getProcessCodeList() {
  const { data } = await request({
    url: `/mdm/mdmprocess/getList`,
    method: "post",
    data: {},
  });
  processCodeList.value = data;
}
function processChange(code: string) {
  // searchParam.value.deviceCode = "";
  searchParam.value.deviceIds = [];
  searchParam.value.parameterName = "";
  searchParam.value.parameterDesc = "";
  searchParam.value.productModel = "";
  if (code) {
    const current: any =
      processCodeList.value?.filter((e: any) => e.processCode === code)[0] ??
      {};
    searchParam.value.processId = current.id || "";
    getEquipList();
  } else {
    equipList.value = [];
    searchParam.value.processId = "";
    getEquipList();
  }
}

// 通过工序查询设备列表
const equipList = ref(<any>[]);
async function getEquipList(id?: string) {
  const res: any = await request({
    // url: "/iotadmin/scaequipinfo/getlist",
    url: "/dmpDosPcm/equipmentInfo/getList",
    method: "post",
    data: {
      processCode: searchParam.value.processCode,
      processId: searchParam.value.processId,
      workshopSectionId: searchParam.value.workshopSectionId,
    },
  });
  if (res.code === 200) {
    equipList.value = res.data;
  }
}
function equipChange(ids: string) {
  searchParam.value.parameterName = "";
  searchParam.value.parameterDesc = "";
  searchParam.value.productModel = "";
  collectParamList.value = [];
  if (ids.length) {
    getCollectParamList();
    getProductList();
  } else {
    searchParam.value.deviceIds = [];
    getProductList();
  }
}

function processTypeChange(id: string) {
  searchParam.value.parameterDesc = "";
  searchParam.value.parameterName = "";

  collectParamList.value = [];
  if (id) {
    getCollectParamList();
  } else {
    getCollectParamList();
  }
}

function processParameterChange(name: string) {
  if (name) {
    const current: any =
      collectParamList.value?.filter((e: any) => e.parameterName === name)[0] ??
      {};
    searchParam.value.parameterDesc = current.parameterDesc || "";
  } else {
    searchParam.value.parameterDesc = "";
  }
}

const collectParamList = ref(<any>[]);
async function getCollectParamList(id?: string) {
  const res: any = await request({
    url: "/iotadmin/scaequipcollectionparam/getProcessParamList",
    method: "post",
    data: {
      paramType: searchParam.value.processDataType,
      relationIds: searchParam.value.deviceIds,
    },
  });
  if (res.code === 200) {
    collectParamList.value = res.data || [];
  }
}

// 更新创建时间
function getPointTime(data: any) {
  if (data) {
    searchParam.value.collectionTimeStart = data[0];
    searchParam.value.collectionTimeEnd = data[1];
  } else {
    searchParam.value.collectionTimeStart = "";
    searchParam.value.collectionTimeEnd = "";
  }
}

// tab点击事件
function tabClickHandle(e) {
  if (e.index == 1) {
    getSingleData();
  }
}

// 获取单值图数据
const singleLoading = ref(false);
const singleData = ref<any>(null);
async function getSingleData() {
  if (!searchParam.value.deviceIds.length) {
    ElMessage.error("请先选择设备");
    return;
  }
  if (!searchParam.value.parameterName) {
    ElMessage.error("请先选择工艺参数");
    return;
  }
  if (!/^(0|[1-9][0-9]*)$/.test(searchParam.value.pointCount)) {
    ElMessage.error("显示点数应为正整数");
    return;
  }
  if (Number(searchParam.value.pointCount) > 10000) {
    ElMessage.error("显示点数不能大于10000");
    return;
  }
  if (!searchParam.value.collectionTimeStart) {
    ElMessage.error("请选择监控时间且不能超过七天");
    return;
  }
  let startTime = dayjs(searchParam.value.collectionTimeStart); // 开始时间
  let endTime = dayjs(searchParam.value.collectionTimeEnd); // 结束时间
  if (endTime.diff(startTime, "hour") > 24 * 7) {
    ElMessage.error("请选择监控时间且不能超过七天");
    return;
  }
  if (!searchParam.value.productModel) {
    ElMessage.warning("请选择产品型号");
    return;
  }
  // if (!searchParam.value.programName) {
  //   ElMessage.warning("请填写程序名");
  //   return;
  // }
  singleData.value = null;
  singleLoading.value = true;
  const { data }: any = await request({
    url: "/dmpDosPcm/psmprocessdata/multiCurve",
    method: "post",
    data: toRaw(searchParam.value),
  })
    .finally(() => {
      singleLoading.value = false;
    })
    .catch((e) => {});
  singleData.value = {
    doubleData: data,
    paramName: searchParam.value.parameterDesc,
  };
  singleLoading.value = false;

  // 模拟
  // singleData.value = {};
  // singleLoading.value = true;
  // setTimeout(() => {
  //   singleData.value = {
  //     doubleData: [getSingleDataMock(100), getSingleDataMock(100)],
  //     paramName: searchParam.value.parameterDesc,
  //   };
  //   console.log("singleData.value", singleData.value);
  //   singleLoading.value = false;
  // }, 1000);
}

onMounted(() => {
  getEquipList();
  getProcessCodeList();
  // 获取产品型号列表
  getProductList();
  getTableList();
  getWorkshopSectionList();
  getProcessEquipList();
});

// 打开工单详情
function openWorkOrder(item: any) {
  if (item.orderNo) {
    openDialogdetail({ id: item.orderNo });
  }
}
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/dmpDosPcm/psmworkorder/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
/** 打开工单管理表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "工单管理详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}
const changeWorkshopSection = () => {
  searchParam.value.processCode = "";
  searchParam.value.processId = "";
  searchParam.value.deviceIds = [];
  searchParam.value.productModel = "";
  processCodeList.value = [];
  getProcessListByWorkshopSection();
  getEquipList();
};

const getProcessListByWorkshopSection = async () => {
  if (searchParam.value.workshopSectionId) {
    await request({
      url: `mdm/mdmworkshopsection/getDetails`,
      method: "post",
      data: { id: searchParam.value.workshopSectionId },
    }).then((res) => {
      processCodeList.value = res.data
        ? res.data.map(({ processId, processCode }) => ({
            id: processId,
            processName: processCode,
            processCode,
          }))
        : [];
    });
  } else {
    await getProcessCodeList();
  }
};

const workshopSectionList = ref([]);
const getWorkshopSectionList = async () => {
  await request({
    url: `mdm/mdmworkshopsection/getList`,
    method: "post",
    data: {},
  }).then((res) => {
    workshopSectionList.value = res.data;
  });
};

// 获取工序列表
const processEquipList: any = ref([]);
async function getProcessEquipList() {
  searchParam.value.processEquipId = "";
  processEquipList.value = [];
  const { data } = await request({
    // url: `/mdm/mdmprocess/getList`,
    url: "/dmpDosPcm/psmparammonitorrule/exist/processEquip/options",
    method: "post",
    data: {
      workshopSectionId: searchParam.value.workshopSectionId,
      processId: searchParam.value.processId,
    },
  });
  processEquipList.value = data;
}

function processEquipChange() {
  getEquipList();
}
</script>

<style lang="scss" scoped>
:deep(.app-container .el-tabs--border-card) {
  box-shadow: 0px 0px 12px rgba(3, 8, 72, 0.08);
  border: none;
}
:deep(.select-device) {
  .el-tag {
    padding: 0 4px;
  }
}
:deep(.el-descriptions--small .el-descriptions__header) {
  margin-top: 12px;
  margin-bottom: 4px;
}
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 100px;
}

.doubleData0 {
  :deep(.el-descriptions__header) {
    margin-top: 0px !important;
  }
}
// .el-tabs:nth-child(2) {
//   :deep(.el-tabs__content) {
//     background-color: aqua;
//     padding: 15px 4px;
//   }
// }
</style>
